package com.hong.serviceorder.aspect;

import com.hong.commonutil.exception.YyghException;
import com.hong.commonutil.result.ResultCodeEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class OrderAspect {
    @Autowired
    private RedissonClient redissonClient;
    //防止用户快速点击导致重复预约检测不出来，同时该服务可能多实例部署所以采用分布式锁
    @Around("execution(public Long com.hong.serviceorder.service.impl.OrderServcieImpl.saveOrder(..))")
    public Object lock(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        String key=(String) args[0] + (Long) args[1];
        System.out.println(key);
        if(args.length==2&&!StringUtils.isEmpty(args[0])&&!StringUtils.isEmpty(args[1])){
            RLock lock = redissonClient.getLock(key);
            try {
                lock.lock(10L, TimeUnit.SECONDS);
                System.out.println("lock");
                Thread.sleep(5000);
                return joinPoint.proceed();
            }finally {
                System.out.println("end");
                lock.unlock();
            }
        }else {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
    }
}
